#include "eventclient.h"
#include <fstream>

std::string EventClient::Dispatch(const std::string &text)
{
    // Data we are sending to the server.
    GrpcEventMessage request;
    request.set_jsontext("saafasfsafsa");

    // Container for the data we expect from the server.
    GrpcEventMessage reply;

    // Context for the client. It could be used to convey extra information to
    // the server and/or tweak certain RPC behaviors.
    ClientContext context;

    // The actual RPC.
    Status status = stub_->Dispatch(&context, request, &reply);

    // Act upon its status.
    if (status.ok()) {
        return reply.jsontext();
    } else {
        qDebug() << status.error_code() << ": " << status.error_message().c_str();
        return "RPC failed";
    }
}

void EventClient::SubDispatch()
{
    GrpcEventMessage request;
    request.set_jsontext("MCU");


    GrpcEventMessage reply;

    ClientContext context;



    std::unique_ptr<ClientReader<GrpcEventMessage> > reader(
        stub_->SubscribeDispatch(&context, request));
    while (reader->Read(&reply)) {
        qDebug() << "Found GrpcEventMessage called " << reply.jsontext().c_str();

        //QMessageBox::critical(nullptr, "assfsf","sdgsgdsg");
    }
    Status status = reader->Finish();
    if (status.ok()) {
        qDebug() << "ListFeatures rpc succeeded." ;
    } else {
        qDebug() << "ListFeatures rpc failed." ;
    }

    qDebug() << "channel state" << status.error_message().c_str();
}


void EventClientTest()
{

    auto  ReadFile = [](const std::string& filename) {
        std::ifstream file(filename);
        if (!file.is_open()) {
            throw std::runtime_error("Unable to open file: " + filename);
        }
        return std::string((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
    };
    // 创建一个使用 HTTPS 的 gRPC 通道
/*
    // 配置 SSL 证书
    grpc::SslCredentialsOptions ssl_opts;
    //ssl_opts.pem_root_certs = ReadFile("certificate.crt"); //  服务器证书
    ssl_opts.pem_root_certs = ReadFile("server.crt"); //  服务器证书
    auto creds = grpc::SslCredentials(ssl_opts);
    // 创建 SSL 凭据
    auto credentials = grpc::SslCredentials(ssl_opts);


    EventClient enent(grpc::CreateChannel(
        "localhost:6001", credentials));
*/

    EventClient enent(grpc::CreateChannel(
        "localhost:6001", grpc::InsecureChannelCredentials()));
    std::string user("world");
       std::string reply = enent.Dispatch(user);
    qDebug() << "Greeter received: " << reply.c_str();


    enent.SubDispatch();
}
